<template>
    <div class="xpage">
        <div class="left_obj">
            <div draggable>
                PCS
            </div>
            <div draggable>
                BMS
            </div>
            <div draggable>
                电表1
            </div>
        </div>

        <div ref="container" id="container" class="my_container"></div>
    </div>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import { Graph } from '@antv/x6';
import localImage from '@/assets/image.png';

let container = ref(null);
let graph = null;

// 图片转Base64函数（优化版）
const imageToBase64 = (imgUrl) => {
  return new Promise((resolve) => {
    const img = new Image();
    img.crossOrigin = 'Anonymous';
    img.onload = () => {
      const canvas = document.createElement('canvas');
      canvas.width = img.width;
      canvas.height = img.height;
      const ctx = canvas.getContext('2d');
      ctx.drawImage(img, 0, 0);
      resolve(canvas.toDataURL('image/png'));
    };
    img.onerror = () => resolve('');
    img.src = imgUrl;
  });
};

// 初始化图形配置
const ports = {
    groups: {
        top: { position: 'top', attrs: { circle: { r: 4, magnet: true, stroke: '#5F95FF', strokeWidth: 1, fill: '#fff', style: { visibility: 'hidden' } } } },
        right: { position: 'right', attrs: { circle: { r: 4, magnet: true, stroke: '#5F95FF', strokeWidth: 1, fill: '#fff', style: { visibility: 'hidden' } } } },
        bottom: { position: 'bottom', attrs: { circle: { r: 4, magnet: true, stroke: '#5F95FF', strokeWidth: 1, fill: '#fff', style: { visibility: 'hidden' } } } },
        left: { position: 'left', attrs: { circle: { r: 4, magnet: true, stroke: '#5F95FF', strokeWidth: 1, fill: '#fff', style: { visibility: 'hidden' } } } },
    },
    items: [
        { group: 'top' },
        { group: 'right' },
        { group: 'bottom' },
        { group: 'left' },
    ],
};

// 注册自定义节点
Graph.registerNode('custom-rect', {
    inherit: 'rect',
    width: 66,
    height: 36,
    attrs: {
        body: { strokeWidth: 1, stroke: '#5F95FF', fill: '#EFF4FF' },
        text: { fontSize: 12, fill: '#262626' },
    },
    ports: { ...ports },
}, true);

// 注册图片+文字节点（优化版）
Graph.registerNode('image-text-node', {
    inherit: 'rect',
    markup: [
        { tagName: 'rect', selector: 'body' },
        { tagName: 'image', selector: 'image' },
        { tagName: 'text', selector: 'text' },
    ],
    attrs: {
        body: { stroke: '#5F95FF', strokeWidth: 1, fill: '#FFFFFF' },
        image: { 'xlink:href': '' },
        text: { fontSize: 12, fill: '#333' },
    },
}, true);

// 创建复合节点（优化版）
const createComplexNode = (graph, config) => {
    const {
        imageUrl,
        text = '',
        width = 120,
        height = 120,
        textStyle = {},
        imageStyle = {},
        ...restConfig
    } = config;

    return graph.createNode({
        shape: 'image-text-node',
        width,
        height,
        attrs: {
            body: { stroke: '#5F95FF', strokeWidth: 1, fill: '#FFFFFF', rx: 6, ry: 6 },
            image: { 
                'xlink:href': imageUrl,
                width: width - 20,
                height: height - 40,
                x: 10,
                y: 10,
                ...imageStyle 
            },
            text: { 
                text: text,
                fontSize: 12,
                fill: '#333',
                refX: 0.5,
                refY: '100%',
                y: -10,
                textAnchor: 'middle',
                ...textStyle 
            },
        },
        ports: ports,
        ...restConfig,
    });
};

onMounted(async () => {
    // 初始化画布
    graph = new Graph({
        panning: { enabled: true, modifiers: 'space', eventTypes: "leftMouseDown" },
        scaling: { min: 0.05, max: 1 },
        mousewheel: { 
            enabled: true, 
            modifiers: ['ctrl', 'meta'],
            guard: (e) => !e.altKey
        },
        grid: { 
            size: 10,
            visible: true,
            args: { color: '#a0a0a0', thickness: 1 }
        },
        container: container.value,
        connecting: { anchor: 'orth' },
    });

    // 将本地图片转换为Base64
    const base64Image = await imageToBase64(localImage);
    if (!base64Image) {
        console.error('图片转换失败');
        return;
    }

    // 创建并添加节点
    setTimeout(async () => {
        // 创建复杂节点（使用Base64图片）
        const complexNode = createComplexNode(graph, {
            imageUrl: base64Image,
            text: '本地图片节点',
            width: 120,
            height: 100
        });
        graph.addNode(complexNode);

        // 创建远程图片节点（对比测试）
        const remoteNode = createComplexNode(graph, {
            imageUrl: 'https://gw.alipayobjects.com/zos/bmw-prod/c55d7ae1-8d20-4585-bd8f-ca23653a4489.svg',
            text: '远程图片节点',
            width: 120,
            height: 100,
            x: 150, // 设置不同位置
            y: 0
        });
        graph.addNode(remoteNode);
    }, 500);
});
</script>

<style scoped>
.xpage {
    height: 100%;
    display: flex;
}

.my_container {
    flex: 1;
    height: 100%;
}

.left_obj {
    background-color: #fff;
    width: 300px;
}

.left_obj>div {
    background-color: aquamarine;
    color: #333;
    text-align: center;
    line-height: 50px;
    border: 1px solid gray;
    border-radius: 10px;
    cursor: move;
    margin-bottom: 20px;
}
</style>